<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
    :maskClosable="false"
  >
    <BasicForm @register="registerForm" style="margin-right: 20px" autoComplete="off" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { CreateMenuParams, UpdateMenuParams } from '@/api/system/model/systemModel';

  import { addMenu, updateMenu, getSelectMenu } from '@/api/system/menu';
  import { getDictionaryList } from '@/api/system/dictionary';

  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';

  defineOptions({ name: 'MenuDrawer' });

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  let menuId: Number;
  let menuParentId: Number;

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    menuParentId = data?.id;
    menuId = data.record?.id;
    console.log(menuParentId);

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    } else {
      setFieldsValue({
        parent_id: menuParentId,
      });
    }
    const treeData = await getSelectMenu();
    updateSchema({
      field: 'parent_id',
      componentProps: { treeData },
    });

    const { items } = await getDictionaryList({ parent_id: 33, order_by: 'order_no:asc' });
    const moduleSelect: any = [];
    items.forEach((item) => {
      moduleSelect.push({
        id: item.id,
        name: item.name,
      });
    });
    updateSchema({
      field: 'module_id',
      componentProps: {
        options: moduleSelect,
      },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const { t } = useI18n();
      // TODO custom api
      if (unref(isUpdate)) {
        let params: UpdateMenuParams = {
          id: menuId,
          parent_id: values['parent_id'],
          name: values['name'],
          url: values['url'],
          perms: values['perms'],
          type: values['type'],
          icon: values['icon'],
          order_no: values['order_no'],
          status: values['status'],
          component: values['component'],
          is_show: values['is_show'],
          path: values['path'],
          module_id: values['module_id'],
          affx: values['affx'],
          redirect: values['redirect'],
        };
        const { code, message } = await updateMenu(params);
        if (code === 0) {
          createMessage.success(t('sys.api.updateSuccess'), 1, () => {
            emit('success');
            closeDrawer();
          });
        } else {
          createMessage.error(message);
        }
      } else {
        let params: CreateMenuParams = {
          parent_id: values['parent_id'],
          name: values['name'],
          url: values['url'],
          perms: values['perms'],
          type: values['type'],
          icon: values['icon'],
          order_no: values['order_no'],
          status: values['status'],
          component: values['component'],
          is_show: values['is_show'],
          path: values['path'],
          module_id: values['module_id'],
          affx: values['affx'],
          redirect: values['redirect'],
        };

        addMenu(params)
          .then(() => {
            createMessage.success(t('sys.api.createSuccess'), 1, () => {
              emit('success');
              closeDrawer();
            });
          })
          .catch((err) => {
            console.log(err);
          });
      }
    } catch (error) {
      console.log(error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
